package com.alibaba.ribbonresttemplate;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

/**
 * @author YL
 * @date 22:34 2021/10/12
 */
@Slf4j
@RestController
@RequestMapping("test")
public class TestController {

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("instances")
    public List<ServiceInstance> instances() {
        List<ServiceInstance> instances = discoveryClient.getInstances("ribbon-server");
        return instances;
    }

    @GetMapping("randomServerUrl")
    public String randomServerUrl() {
        List<ServiceInstance> instances = discoveryClient.getInstances("ribbon-server");
        List<String> urls = instances.stream().map(s -> s.getUri().toString()).collect(Collectors.toList());
        int i = ThreadLocalRandom.current().nextInt(urls.size());
        String requestUrl = urls.get(i).concat("/user/sayHello");
        log.info("request url=" + requestUrl);
        String forObject = restTemplate.getForObject(requestUrl, String.class);
        return forObject;
    }

    @GetMapping("serviceId")
    public String serviceId(){
        return restTemplate.getForObject("http://ribbon-server/user/sayHello", String.class);
    }
}
